<script lang="ts" setup>
// 科室查询
import { onMounted, ref, defineProps, defineEmits } from 'vue';
import { Delete, Plus, Search,Refresh,EditPen } from '@element-plus/icons-vue'
import { ElTable } from 'element-plus'
// 分页
import type { ComponentSize,TableInstance } from 'element-plus'
import { formatDate } from '@/utils/dateFormatter';//引入全局日期格式化工具
import http from '@/http'
import { useCookies } from '@vueuse/integrations/useCookies'
import { Value } from 'sass-embedded';
import { tr } from 'element-plus/es/locale';
import { ElMessage } from 'element-plus'; // 引入消息组件
const PageNum = ref(1)
const pageSize = ref(3)
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)
const cookies=useCookies();
//每页条数
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  pageSize.value=val
  sysDeptPageInfo();
}
//分页页码
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  PageNum.value=val
  sysDeptPageInfo();
}

const tableData=ref([])
const total=ref()
// 科室名称：
const name = ref("")
// 状态：
const status = ref('')
//下拉框默认值
const options2 = ref([
{
    value: '',
    label: '全部',
  },
  {
    value: '0',
    label: '可用',
  },
  {
    value: '1',
    label: '禁用',
  }
])
//封装分页查询的方法
function sysDeptPageInfo(){
    //发送get请求获取当前页的消息
    http.get("/dept/sysDeptPageInfo?pageNum="+PageNum.value+"&PageSize="+pageSize.value+"&deptName="+name.value+"&status="+status.value).then((res)=>{
        console.log("成功")
        tableData.value=res.list;
        total.value=res.total
        ids.value=res.list
    }).catch(()=>{ 
        console.log("失败")
    })
}
//挂载完成之后调用分页查询方法  
onMounted(()=>{
    sysDeptPageInfo();
})
//重置搜索框与状态方法
function reset(){
    name.value=status.value=''
}
// 删除
// 发送 DELETE 请求，更改科室状态
function remove() {
    if (multipleSelection.value.length === 0) {
        console.warn("请选择要删除的科室");
        return;
    }

    http.delete("/dept/sysDeptRemove", {
        params: { deptIds: multipleSelection.value.join(',') } // 将数组转换为逗号分隔的字符串
    }).then((res) => {
        console.log("删除成功", res.data);
        // 删除成功后刷新数据
        sysDeptPageInfo();
    }).catch((error) => {
        console.error("删除失败", error);
    });
}

function ha() {
    console.log("A")
}

// 复选框id
let ids = ref([])

interface dept {
  id: number
  date: string
  name: string
  address: string
}

// 表格的元素引用
const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref<number[]>([]) // 存储选中的 deptId

// 获取选中的用户
const handleSelectionChange = (val: dept[]) => {
  console.log("选中的行数据:", val);
  // 使用 map 方法从选中的行数据中提取 deptId，并将这些 deptId 存储在 multipleSelection 数组中
  multipleSelection.value = val.map(row => row.deptId);
  console.log("选中的 deptId:", multipleSelection.value);
}

// 全选和全不选
const toggleSelection = (rows?, ignoreSelectable?: boolean) => {
  if (rows) {
    rows.forEach((row) => {
      multipleTableRef.value!.toggleRowSelection(
        row,
        undefined,
        ignoreSelectable
      )
    })
  } else {
    multipleTableRef.value!.clearSelection()
  }
}
//滑动单选框

// 切换开关状态
const toggleSwitch = (deptId,status) => {
  // isChecked.value = !isChecked.value;

  // emit('update:modelValue', isChecked.value); // 触发双向绑定更新
  //发送http请求修改科室状态
  http.get("/dept/setStatus?deptId="+deptId+"&status="+status).then((res)=>{
    console.log("成功",res)
    sysDeptPageInfo();
  }).catch((res)=>{
    console.log("失败",res)
  }).finally(()=>{
      sysDeptPageInfo();
    })
};
//控制添加模态框
const dialogVisible = ref(false)
// 添加模态框对象
const form = ref({
  deptName: '',
  depnumber: '',
  deptLeader: '',
  leaderPhone: '',
  orderNum: 0,
  status: '0',
  uid:''
});

// 表单验证函数
const validateForm = () => {
  if (!form.value.deptName) {
    return false;
  }
  // 可以添加更多的验证逻辑，例如验证电话号码格式等
  return true;
};

const submitForm = () => {
  if (!validateForm()) {
    return;
  }
  // 提交表单逻辑，例如发送请求到后端
  console.log(':', form.value);
  form.value.uid=cookies.get("token");
  // 发送 POST 请求到后端
  http.post("/dept/addDept", form.value)
  .then((res) => {
      console.log(res.data.message);
      ElMessage({
        message: res.message,
        type: 'success',
        duration: 3000
      });
    })
    .catch((res) => {
      console.error('请求出错:', res.message);
      if (res.message) {
        ElMessage.error(`请求失败：${res.message || '未知错误'}`);
      } else {
        ElMessage.error('网络连接异常，请检查网络');
      }
    }).finally(()=>{
      sysDeptPageInfo();
    });
};
//修改dialogVisible2模态框控制属性
let dialogVisible2=ref(false);
const form2 = ref({
  deptId:'',
  deptName: '',
  depnumber: '',
  deptLeader: '',
  leaderPhone: '',
  orderNum: 0,
  status: '0',
  uid:''
});

const submitForm2 = () => {
  http.post("/dept/setDept", form2.value)
    .then((res) => {
      console.log(res.data.message);
      ElMessage({
        message: res.message,
        type: 'success',
        duration: 3000
      });
    })
    .catch((res) => {
      console.error('请求出错:', res.message);
      if (res.message) {
        ElMessage.error(`请求失败：${res.message || '未知错误'}`);
      } else {
        ElMessage.error('网络连接异常，请检查网络');
      }
    });
};

const resetForm = () => {
  form2.value = {
    deptId:'',
    deptName: '',
  depnumber: '',
  deptLeader: '',
  leaderPhone: '',
  orderNum: 0,
  status: '0',
  uid:''
  };
};
//修改按钮
function updateDept(depid){
//发送http请求根据id获取返回对象
http.get("/dept/selectById?depid="+depid).then((res)=>{
console.log("成功",res)
//给修改模态框对象赋值
form2.value.deptId=res.deptId;
form2.value.deptName=res.deptName;
form2.value.depnumber=res.deptNumber;
form2.value.deptLeader=res.deptLeader;
form2.value.leaderPhone=res.leaderPhone;
form2.value.orderNum=res.orderNum;
form2.value.status=res.status;
form2.value.uid=cookies.get("token");
//显示模态框
dialogVisible2.value=true;
}).catch((res)=>{
console.log("失败")
})
}
</script>

<template>
    <!-- 头部搜索 -->
  <el-row>
    <el-col :span="24">
        科室名称：<el-input v-model="name" style="width: 240px" placeholder="Please input" /> 
        状态：
        <el-select
      v-model="status"
      placeholder="全部"
      size="large"
      style="width: 240px"
      clearable
    >
      <el-option
        v-for="item in options2"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
        <el-button :icon="Search" type="primary" @click="sysDeptPageInfo()">搜索</el-button> <el-button :icon="Refresh" type="primary" @click="reset()">重置</el-button>
    </el-col>
  </el-row>
  <!-- 添加 修改 删除 -->
  <el-row>
    <el-col :span="14"> 
        <el-button :icon="Plus" type="primary" @click="dialogVisible = true" >添加</el-button>
        
        <el-button :icon="Delete" type="danger" plain @click="remove()">删除</el-button>
    </el-col>
  </el-row>
  <!--  主体内容-->
  <el-row>
    <el-col :span="24"> 
    <el-table :data="tableData" style="width: 100%" border stripe ref="multipleTableRef" row-key="deptId"
    @selection-change="handleSelectionChange" v-model="tableData.deptId">

    <el-table-column type="selection" width="55" >

    </el-table-column>
    <el-table-column label="科室ID" width="120">
      <template #default="scope">{{ scope.row.deptId }}</template>
    </el-table-column>
    <el-table-column property="deptName" label="科室名称" width="120" >
        <template #default="scope">{{ scope.row.deptName }}</template>
     </el-table-column>
    <el-table-column property="deptNumber" label="科室编码" width="140" show-overflow-tooltip>
        <template #default="scope">{{ scope.row.deptNumber }}</template>
        </el-table-column>  
    <el-table-column property="regNumber" label="当前挂号量" width="140" >
        <template #default="scope">{{ scope.row.regNumber }}</template>
    </el-table-column>
    <el-table-column property="name" label="负责人" width="120" >
        <template #default="scope">{{ scope.row.deptLeader }}</template>
    </el-table-column>
    <el-table-column property="leaderPhone" label="电话" width="140" show-overflow-tooltip>
        <template #default="scope">{{ scope.row.leaderPhone }}</template>
        </el-table-column>
    <el-table-column property="status" label="状态" width="200px">
      <template #default="scope">
        <!-- 滑动单选框容器 -->
  <div class="custom-switch" @click="toggleSwitch(scope.row.deptId,scope.row.status)">
    <!-- 滑动轨道 -->
    <div class="switch-track" :class="{ 'active':  scope.row.status!=1 }">
      <!-- 滑动按钮 -->
      <div class="switch-thumb" :class="{ 'active': scope.row.status!=1 }"></div>
    </div>
    <!-- 可选：状态文本 -->
    <span class="state-text">{{  scope.row.status!=1 ? '禁用' : '可用' }}</span>
  </div>
</template>
        </el-table-column>
    <el-table-column property="createTime" label="创建时间" width="180" >
        <template #default="scope">{{formatDate( scope.row.createTime,'YYYY年MM月DD日 HH:mm' )}}</template>
        </el-table-column>
    <el-table-column property="address" label="操作" width="240" show-overflow-tooltip>
      <template #default="scope">
        <el-button :icon="EditPen" type="success" @click="updateDept(scope.row.deptId)"  plain>修改</el-button>
      </template>
        </el-table-column>
  </el-table>
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="PageNum"
        v-model:page-size="pageSize"
        :page-sizes="[1,2,3]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" 
      />
    </div>
    </el-col>
  </el-row>
  <el-dialog
    v-model="dialogVisible"
    modal-class="overide-animation"
    :before-close="
      (doneFn) => {
        console.log('before-close'), doneFn()
      }
    "
    @open="console.log('open')"
    @open-auto-focus="console.log('open-auto-focus')"
    @opened="console.log('opened')"
    @close="console.log('close')"
    @close-auto-focus="console.log('close-auto-focus')"
    @closed="console.log('closed')"
  >
    <span>
      <el-form :model="form" label-width="120px">
    <el-form-item label="科室名称">
      <el-input v-model="form.deptName" placeholder="请输入科室名称"></el-input>
    </el-form-item>
    <el-form-item label="科室编码">
      <el-input v-model="form.depnumber" placeholder="请输入科室编码"></el-input>
    </el-form-item>
    <el-form-item label="负责人">
      <el-input v-model="form.deptLeader" placeholder="请输入负责人"></el-input>
    </el-form-item>
    <el-form-item label="负责人电话">
      <el-input v-model="form.leaderPhone" placeholder="请输入负责人电话"></el-input>
    </el-form-item>
    <el-form-item label="排序码">
      <el-input v-model="form.orderNum" type="number" placeholder="排序码（默认为0）" :value="form.orderNum || 0"></el-input>
    </el-form-item>
    <el-form-item label="状态">
      <el-radio-group v-model="form.status">
        <el-radio label="0">正常</el-radio>
        <el-radio label="1">停用</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">确定</el-button>
      <el-button >取消</el-button>
    </el-form-item>
  </el-form>

    </span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="dialogVisible = false">
          Confirm
        </el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog
    v-model="dialogVisible2"
    modal-class="overide-animation"
    :before-close="
      (doneFn) => {
        console.log('before-close'), doneFn()
      }
    "
    @open="console.log('open')"
    @open-auto-focus="console.log('open-auto-focus')"
    @opened="console.log('opened')"
    @close="console.log('close')"
    @close-auto-focus="console.log('close-auto-focus')"
    @closed="console.log('closed')"
  >
    <span>
      <div class="form-container">
    <el-form :model="form2" label-width="80px" label-position="left">
      <!-- 科室名称 -->
      <el-form-item label="科室名称">
        <el-input v-model="form2.deptName" placeholder="内科" />
      </el-form-item>

      <!-- 电话和科室编码 -->
      <el-row :gutter="20">
        <!-- <el-col :span="12">
          <el-form-item label="电话">
            <el-input v-model="form.leaderPhone" placeholder="15902738715" />
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="科室编码">
            <el-input v-model="form2.depnumber" placeholder="HIS-NK" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 负责人和电话 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="负责人">
            <el-input v-model="form2.deptLeader" placeholder="雷哥" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电话">
            <el-input v-model="form2.leaderPhone" placeholder="15902738715" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 排序码和状态 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="排序码">
            <el-input-number 
              v-model="form2.orderNum" 
              :min="1" 
              controls-position="right"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态">
            <el-radio-group v-model="form2.status">
              <el-radio value="0" label="正常" />
              <el-radio value="1"   label="停用" />
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
<!--  -->
      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm2">确定</el-button>
        <el-button @click="dialogVisible2=false" >取消</el-button>
      </el-form-item>
    </el-form>
  </div>

    </span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="dialogVisible = false">
          Confirm
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
/* 容器样式 */
.custom-switch {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  user-select: none;
}

/* 滑动轨道 */
.switch-track {
  width: 60px;
  height: 30px;
  background-color: #e0e0e0;
  border-radius: 15px;
  position: relative;
  transition: background-color 0.3s ease;
}

/* 激活状态的轨道颜色 */
.switch-track.active {
  background-color: #4CAF50; /* 可自定义激活颜色 */
}

/* 滑动按钮 */
.switch-thumb {
  width: 26px;
  height: 26px;
  background-color: white;
  border-radius: 50%;
  position: absolute;
  top: 2px;
  left: 2px;
  transition: transform 0.3s ease;
  box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

/* 激活状态的按钮位置 */
.switch-thumb.active {
  transform: translateX(30px); /* 根据轨道宽度调整 */
}

/* 状态文本样式 */
.state-text {
  font-size: 14px;
  color: #666;
  font-weight: bold;
}
/* Add your styles here */
.dialog-footer {
  text-align: right;
}
/* 修改模态框 */
.form-container {
  padding: 20px;
  max-width: 600px;
}

.el-input-number {
  width: 100%;
}

.el-radio-group {
  margin-top: 5px;
}
</style>

